//用户状态
{
  window.onload = function () {
    let oLogin = document.querySelector('.login1')
    let flag = localStorage.getItem('token')
    let user = localStorage.getItem('user')
    if (flag) {
      oLogin.innerHTML = `<a class="red" href="javascript:;">Hi, ${user}</a><a class="exit" href="javascript:;">&nbsp;&nbsp; [退出]&nbsp;&nbsp;</a><em class="card"></em><a href="./html/shopping.html">购物车</a>&nbsp;<b class='red'></b>`

      let oExit = document.querySelector('.exit')

      oExit.addEventListener('click', function () {
        localStorage.removeItem('user')
        localStorage.removeItem('token')
        location.reload()
      })
      // 购物车数据
      let shopCarCount = document.querySelector('.welcome b')
      // 购物车里面
      if (localStorage.getItem('shopArr') === null) {
        var count = 0
      } else {
        count = JSON.parse(localStorage.getItem('shopArr')).length
      }
      shopCarCount.innerHTML = count
    }
  }
}
//导航二级
{
  let province = document.querySelector('.province')
  let goWhere = document.querySelector('.go-where')
  //初始化
  ajax({
    url: '../../Dangdangshopping/data/province.json',
    success(res) {
      let obj = JSON.parse(res).data
      goWhere.innerHTML = `送至： ${obj[0]}`
      //渲染省份
      obj.forEach(ele => {
        province.innerHTML += `<li><a href="javascript:;">${ele}</a></li>`
      })
      //更换省份
      province.addEventListener('click', e => {
        goWhere.innerHTML = `送至： ${e.target.innerText}`
      })
      goWhere.addEventListener('mouseover', () => {
        province.style.display = 'block'
      })
      goWhere.addEventListener('mouseout', () => {
        province.style.display = 'none'
      })
      province.addEventListener('mouseover', () => {
        province.style.display = 'block'
      })
      province.addEventListener('mouseout', () => {
        province.style.display = 'none'
      })
    },
  })
  //导航栏初始化
  let navRight = document.querySelector('.nav-right')
  ajax({
    url: '../../Dangdangshopping/data/nav.json',
    success(res) {
      let obj = JSON.parse(res).data
      obj.forEach((ele, index) => {
        navRight.innerHTML += `<li>
    <a href="javascript:;" class="${ele.erJi ? 'bg' : ''}"
    data-s=${ele.erJi ? index : null}>
    ${ele.msg}</a>
    <div class="nav-list-right"></div></li>`
      })
      let navErj = navRight.querySelectorAll('.nav-list-right')
      //生成二级
      navRight.addEventListener('mouseover', e => {
        if (e.target.tagName === 'A') {
          if (e.target.dataset.s !== 'null') {
            let erJ = e.target.parentNode.children[1]
            let erJN = obj[e.target.dataset.s].erJi.msg
            erJ.innerHTML = ''
            for (let i = 0; i < erJN.length; i++) {
              erJ.innerHTML += `<p>${erJN[i]}</p>`
            }
            erJ.style.display = 'block'
          }
        }
      })
      navRight.addEventListener('mouseout', e => {
        if (e.target.tagName === 'A') {
          e.target.nextElementSibling.style.display = 'none'
        }
      })
      navErj.forEach(ele => {
        ele.addEventListener('mouseover', e => {
          ele.style.display = 'block'
        })
        ele.addEventListener('mouseout', e => {
          ele.style.display = 'none'
        })
      })
    },
  })
}
//搜索框
{
  let searchSpan = document.querySelector('.search span')
  let selectPop = document.querySelector('.search .select_pop')
  //初始化
  ajax({
    url: '../../Dangdangshopping/data/search.json',
    success(res) {
      let obj = JSON.parse(res).data
      searchSpan.innerHTML = obj[0]
      obj.forEach(ele => {
        selectPop.innerHTML += `<a href="javascript:;">${ele}</a>`
      })
      searchSpan.addEventListener('mouseover', () => {
        selectPop.style.display = 'block'
      })
      searchSpan.addEventListener('mouseout', () => {
        selectPop.style.display = 'none'
      })
      selectPop.addEventListener('mouseover', () => {
        selectPop.style.display = 'block'
      })
      selectPop.addEventListener('click', e => {
        searchSpan.innerHTML = e.target.innerText
      })
      selectPop.addEventListener('mouseout', () => {
        selectPop.style.display = 'none'
      })
    },
  })

  //热搜数据
  let hotSearch = [
    '开口说话绘本',
    '百丽童鞋',
    '三只松鼠',
    '世界喧嚣',
    '透视世界',
    '今日抢购',
  ]
  //初始化
  let hotSech = document.querySelector('.search_bottom')
  hotSech.innerHTML = `<a href="javascript:;">热搜:</a>`
  hotSearch.forEach(ele => {
    hotSech.innerHTML += `<a href="javascript:;">${ele}</a>`
  })
  hotSech.innerHTML += `<a href="javascript:;">高级搜索</a>`
}
//模糊查询
{
  let search = document.querySelector('#logo input')
  let btn = document.querySelector('#logo button')
  let mainItemLeft = document.querySelector('.main_item_left')
  let xhr = new XMLHttpRequest()
  function getData(n, txt) {
    mainItemLeft.innerHTML = ''
    xhr.open('get', `../server/getList.php?num=${n}&limit=32&txt=${txt}`, true)

    xhr.send()

    xhr.onload = function () {
      let str = xhr.responseText
      // 把字符串变成可用对象
      let arr = JSON.parse(str)

      arr.forEach(ele => {
        mainItemLeft.innerHTML += `<div class="item">
                <img src="${ele.list_big_pic}" alt="" listId="${ele.list_id}"/>
                <div class="pic_list_show">
                  <img src="${ele.list_small_pic}" alt=""/>
                </div>
                  <p class="price">¥${ele.list_price}</p>
                <p class="name">${ele.list_name}</p>
                <p class="search">${ele.list_introduce}</p>
                <img src="../images/listImages/3.jpg" alt="" />
                <span>${1}条评论</span>
                <p class="link">${ele.list_shop}</p>
                <a href="javascript:;"><b class="shopCar" goodsId="${
                  ele.list_id
                }"><i></i>加入购物车</b></a>
                <b class="soucang">收藏</b>
            </div>`
      })
    }
  }

  search.addEventListener('keydown', e => {
    if (e.keyCode === 13) {
      getData(1, search.value)
    }
  })
  btn.addEventListener('click', () => {
    getData(1, search.value)
  })
}
//购物车
{
  // 购物车数据
  let shopCarCount = document.querySelector('.char b')
  // 购物车里面
  if (localStorage.getItem('shopArr') === null) {
    var count = 0
  } else {
    count = JSON.parse(localStorage.getItem('shopArr')).length
  }
  shopCarCount.innerHTML = count
}
//渲染列表 分页
{
  layui.use(function () {
    var laypage = layui.laypage,
      $ = layui.jquery

    let oList = document.querySelector('.main_item_left')

    // 使用jquery的ajax
    // 异步
    $.ajax({
      url: '../server/list.php',
      type: 'get',
      data: {
        num: 1,
        limit: 32,
      },
      success(res) {
        let obj = JSON.parse(res)
        page(obj.count)
      },
    })

    // 同步
    //完整功能
    function page(count) {
      laypage.render({
        elem: 'paging',
        count: count,
        layout: ['prev', 'page', 'next', 'skip'],
        limit: 32,
        jump: function (obj) {
          $.ajax({
            url: '../server/list.php',
            type: 'get',
            data: {
              num: obj.curr,
              limit: 32,
            },
            success(res) {
              let obj = JSON.parse(res)
              shopArr = obj.data
              oList.innerHTML = ''
              obj.data.forEach(ele => {
                oList.innerHTML += `<div class="item">
                <img src="${ele.list_big_pic}" alt="" listId="${ele.list_id}"/>
                <div class="pic_list_show">
                  <img src="${ele.list_small_pic}"  alt=""/>
                  <img src="${
                    ele.list_small_pic2 ? ele.list_small_pic2 : 'dell'
                  }" alt=""/>
                  <img src="${
                    ele.list_small_pic3 ? ele.list_small_pic3 : 'dell'
                  }" alt=""/>
                </div>
                <p class="price">¥${ele.list_price}</p>
                <p class="name">${ele.list_name}</p>
                <p class="search">${ele.list_introduce}</p>
                <img src="../images/listImages/3.jpg" alt="" />
                <span>${ele.list_id}条评论</span>
                <p class="link">${ele.list_shop}</p>
                <a href="javascript:;"><b class="shopCar" goodsId="${
                  ele.list_id
                }"><i></i>加入购物车</b></a>
                <b class="soucang">收藏</b>
            </div>`
              })
              let dell = document.querySelectorAll('.pic_list_show img')
              dell.forEach(ele => {
                ele.src === 'http://localhost/Dangdangshopping/html/dell'
                  ? ele.remove()
                  : ''
              })
            },
          })
        },
      })
    }

    let newArr = JSON.parse(localStorage.getItem('shopArr')) || []

    oList.addEventListener('click', function (ev) {
      if (ev.target.tagName === 'IMG') {
        let cId = ev.target.getAttribute('listId')
        localStorage.setItem('cId', JSON.stringify(shopArr[(cId % 32) - 1]))
        location.href = '../html/detail.html'
      }
      if (ev.target.className === 'shopCar') {
        let id = ev.target.getAttribute('goodsId')
        // filter 接收一个返回值：数组，符合条件的组成一个数组
        let obj = shopArr.filter(ele => id === ele.list_id)[0]
        // 是否存到新数组里面取决于新数组里有没有
        for (let i = 0; i < newArr.length; i++) {
          // 新数组里面肯定有
          if (id === newArr[i].list_id) {
            newArr[i].count++
            // 存到本地
            localStorage.setItem('shopArr', JSON.stringify(newArr))
            alert('添加成功')
            return
          }
        }

        // 能执行到这里，新数组里面肯定没有
        newArr.push({
          count: 1,
          ...obj,
        })

        // 存到本地
        localStorage.setItem('shopArr', JSON.stringify(newArr))
        alert('添加成功')
      }
    })
  })
}
